//
//  SignInViewController.m
//  mUBB
//
//  Created by Cosmin Stirbu on 2/24/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "SignInViewController.h"
#import "NSString+Empty.h"
#import "UserManager.h"
#import "WSError.h"
#import "HomeViewController.h"


@interface SignInViewController ()

@end

@implementation SignInViewController

@synthesize emailTextField, passwordTextField, signInButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // Set up the UI
    self.title = NSLocalizedString(@"SIGN_IN_TITLE", nil);
   [Utils customizeButton:signInButton withBgImageKey:@"button_image" imageKey:nil textKey:@"SIGN_IN_BUTTON" textColorKey:@"welcome_screen_buttons_text_color"];
    
    emailTextField.placeholder = NSLocalizedString(@"EMAIL_PLACEHOLDER", nil);
    passwordTextField.placeholder = NSLocalizedString(@"PASSWORD_PLACEHOLDER", nil);
}

#pragma mark - User Interaction

- (IBAction)signInButtonPressed:(id)sender {
    [self signInUser];
}

#pragma mark - Text Field Delegate Methods

- (IBAction)returnKeyPressed:(id)sender {
    if (sender == emailTextField) {
        // Set focus on password
        [passwordTextField becomeFirstResponder];
    } else {
        [self signInUser];
    }
}


#pragma mark - Private methods

- (void)signInUser {
    // Hide Keyboard
    [emailTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
    
    // Check if email is valid
    if ([Utils isEmailValid:emailTextField.text]) {
        // Check if password is empty
        if (![passwordTextField.text isEqual: @""]) {
            [Utils showLoadingOn:self];
            [[UserManager instance] signInUserEmail:emailTextField.text withPassword:passwordTextField.text userType:UserTypeTeacher delegate:self];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"MESSAGE_PLEASE_ENTER_PASSWORD", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles:nil];
            [alertView show];
        }
    } else {
        NSString *message;
        if ([NSString isNullOrEmpty:emailTextField.text]) {
            message = NSLocalizedString(@"MESSAGE_PLEASE_ENTER_EMAIL", nil);
        } else {
            message = NSLocalizedString(@"MESSAGE_INVALID_EMAIL", nil);
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles:nil];
        [alertView show];
    }
}

#pragma mark - User Protocol delegate methods

- (void)didSignInUserWithSuccessForTicket:(Ticket *)ticket {
    //Hide loading cover
    [Utils hideLoadingOn:self];
    
    // Check if the user didn't leave the screen
    if (!_isOnScreen)
        return;
    
    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:homeViewController];
    navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:navigationController animated:YES];
}

- (void)didSignInUserWithFailure:(id)object forTicket:(Ticket *)ticket {
    // Hide loading cover
    [Utils hideLoadingOn:self];
    
    // Check if the user didn't leave the screen
    if (!_isOnScreen)
        return;
    
    WSError *error = (WSError *)object;
    if (error.errorCode == StatusCodeConnectionError) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"ALERT_RETRY", nil), nil];
        [alertView show];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles: nil];
        [alertView show];
    }
}


#pragma - UIAlertView Delegate Methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        [self signInUser];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setEmailTextField:nil];
    [self setPasswordTextField:nil];
    [self setSignInButton:nil];
    [super viewDidUnload];
}
@end
